/*
 * Copyright 2007 Rob Nielsen
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.proxymatic.core.util;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;

public class StringUtil {
    public static String sentence(Object... objects) {
        return sentence(Arrays.asList(objects));
    }

    public static String sentence(Collection objects) {
        return sentenceQuote(objects, "");
    }

    public static String sentenceQuote(Collection objects, String quote) {
        if (objects.size() == 0) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        int pos = 0;
        int size = objects.size();
        for (Object object : objects) {
            if (pos > 0 && pos == size - 1) {
                sb.append(" and ");
            } else if (pos > 0) {
                sb.append(", ");
            }
            sb.append(quote);
            sb.append(object);
            sb.append(quote);
            pos++;
        }
        return sb.toString();
    }

    public static String shortName(Class cla) {
        if (cla.isArray()) {
            return shortName(cla.getComponentType()) + "[]";
        }
        if (cla.isPrimitive()) {
            return cla.getName();
        }
        String packageName = cla.getPackage().getName();
        return cla.getName().substring(packageName.length() + 1).replaceAll("\\$", ".");
    }

    public static String shortMethod(Method method) {
        StringBuilder sb = new StringBuilder().append(shortName(method.getReturnType())).append(" ").append(method.getName()).append("(");
        Class<?>[] classes = method.getParameterTypes();
        for (int i = 0; i < classes.length; i++) {
            if (i > 0) {
                sb.append(",");
            }
            sb.append(shortName(classes[i]));
        }
        sb.append(')');
        return sb.toString();
    }
}
